<template>
  <div class="sub-category">
    <div class="container">
        <bread separator=">">
            <bread-item to="/">首页</bread-item>
            <bread-item :to="`/category/${parentId}`">{{ subList.parentName }}</bread-item>
            <bread-item>{{ subList.name }}</bread-item>
       </bread>
       <subFilter :subList="subList" @filterChange="filterChangeFn"/>
       <SubSort @sortChange="sortChangeFn"></SubSort>
       <div class="sort-list-container">
        <goods-item v-for="goods in sortList" :key="goods.id" :goods="goods"></goods-item>
       </div>
       <infinite :isloading="isloading" :isFinished="isFinished" :load="sortList"></infinite>
    </div>
  </div>
</template>

<script setup >
import { getCategorySubAPI, getCategorySubSortAPI } from '@/api'
import { useRoute } from 'vue-router'
import { ref } from 'vue'
import subFilter from './components/subFilter.vue'
import SubSort from './components/subSort.vue'

const route = useRoute()
const subList = ref({})
const parentId = ref('')
// 获取二级分类数据
const getCategorySubFn = async() => {
  const res = await getCategorySubAPI(route.params.id)
  //   console.log(res)
  //   给品牌添加全部,补充selected
  res.result.brands.forEach(item => { item.selected = false })
  res.result.brands.unshift({ id: null, name: '全部', selected: true })
  //   给其他添加全部,补充selected
  res.result.saleProperties.forEach(item => {
    item.properties.forEach(it => { it.selected = false })
    item.properties.unshift({ id: null, name: '全部', selected: true })
  })

  subList.value = res.result
  parentId.value = res.result.parentId
}
getCategorySubFn()

// 获取商品列表查询
let sortData = {
  categoryId: route.params.id,
  inventory: false,
  onlyDiscount: false,
  brandId: null,
  attrs: [],
  sortField: null,
  sortMethod: 'desc',
  page: 1,
  pagsize: 20

}
const sortList = ref([])
const isloading = ref(false)
const isFinished = ref(false)
const getCategorySubSortFn = async () => {
  isloading.value = true
  const res = await getCategorySubSortAPI(sortData)
  // console.log(res)
  sortList.value.push(...res.result.items)
  sortData.page++
  if (res.result.items.length === 0) {
    isFinished.value = true
  }
  isloading.value = false
}
getCategorySubSortFn()

// 筛选查询
const filterChangeFn = (filterData) => {
  // console.log('父组件收到了', filterData)
  sortData.brandId = filterData.brandId
  sortData.attrs = filterData.attrs
  sortData.page = 1
  sortList.value = []
  isFinished.value = false
  getCategorySubSortFn()
}

const sortChangeFn = (sortList) => {
  // console.log('父组件收到了', sortList)
  sortData = { ...sortData, ...sortList }
  sortData.page = 1
  sortList.value = []
  isFinished.value = false
  getCategorySubSortFn()
}
</script>

<style scoped lang="less">
 .goods-list{
    background-color: #fff;
    padding: 0 25px;
    margin-top: 25px;
 }
 .sort-list-container{
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-start;
  background-color: #fff;
  padding: 30px 65px ;
 }
</style>
